<script>
  let flatArr = [
    {
      id: 1,
      name: "北京",
      parentId: 0,
    },
    {
      id: 4,
      name: "南京",
      parentId: 2,
    },
    {
      id: 5,
      name: "徐州",
      parentId: 2,
    },
    {
      id: 6,
      name: "扬州",
      parentId: 2,
    },
    {
      id: 2,
      name: "江苏",
      parentId: 0,
    },
    {
      id: 9,
      name: "汊河",
      parentId: 7,
    },
    {
      id: 7,
      name: "滁州",
      parentId: 3,
    },
    {
      id: 8,
      name: "合肥",
      parentId: 3,
    },
    {
      id: 3,
      name: "安徽",
      parentId: 0,
    },
  ];

  //扁平数据转成树形 先找父节点，还得区分1级的节点

  //每条数据只有一根数据
  //currentKey 当前节点的字段标识（属性名）
  //parentKey 父节点的字段标识（属性名）
  //childKey
  function toTree(
    data,
    currentKey = "id",
    parentKey = "parentId",
    childKey = "children"
  ) {
    //储存树形的数组
    let treeArr = [];
    //在粗声明一个函数
    function recursion(data) {
      data.forEach((item) => {
        //判断如果这是一个子节点
        if (item[parentKey]) {
          //子节点找父节点
          let parent = data.find((p) => p[currentKey] === item[parentKey]);
          //再判断父节点是否有子节点children属性
          if (!parent[childKey]) {
            parent[childKey] = [];
          }
          parent[childKey].push(item);
        } else {
          treeArr.push(item);
        }
      });
    }
    recursion(data);
    return treeArr;
  }
  let tree = toTree(flatArr);
  console.log(tree);
</script>
